#include "Example_Mass_Spring_Simulation_Timeline.h"

/* Qt Includes */
#include <QGridLayout>

/* Sx Library Includes */
#include <sxOpenGL_DefaultCameraRenderer.h>
#include <sxOpenGL_DefaultPlotAxesRenderer.h>
#include <sxOpenGL_PickingController.h>
#include <sxOpenGL_Canvas.h>
#include <sxOpenGL_DefaultCuboidRenderer.h>
#include <sxOpenGL_DefaultBezierCurveRenderer.h>
#include <sxOpenGL_DefaultCuboidRenderer.h>
#include <sxOpenGL_DefaultCameraRenderer.h>
#include <sxMassSpringSimulationController.h>
#include <sxOpenGL_DefaultMassSpringMeshRenderer.h>
#include <sxSelfCCD_MSM_CollisionDetectionHandler.h>
#include <sxMSM_TS_CollisionModel.h>
#include <sxMSM_TS_InverseVelocityResponseHandler.h>
#include <sxOBJ_VegaMassSpringMeshStorage.h>
#include <sxVega_TetgenMassSpringMeshStorage.h>
#include <sxCollisionModel.h>
#include <sxDiscreteCollisionModel.h>
#include <sxTriangleSoupCollisionModel.h>
#include <sxMassSpringMesh.h>
#include <sxMassSpringSimulation.h>
#include <sxInverseVelocityResponseHandler.h>
#include <sxEulerCollisionEventPoolAllocator.h>

/* Sx Library Types. */
using Sx::QtInterface::QOpenGL_Viewport;
using Sx::Multimedia::Interface::FixedTimelineController;
using Sx::OpenGL::Graphics::Contexts::OpenGL_Context;
using Sx::OpenGL::Graphics::Objects::Rendering::OpenGL_DefaultCameraRenderer;
using Sx::OpenGL::Graphics::Picking::OpenGL_PickingController;
using Sx::OpenGL::Graphics::Objects::Rendering::OpenGL_DefaultPlotAxesRenderer;
using Sx::OpenGL::Graphics::Objects::Rendering::OpenGL_DefaultBezierCurveRenderer;
using Sx::OpenGL::Interface::OpenGL_Canvas;
using Sx::OpenGL::Graphics::Objects::Rendering::OpenGL_DefaultCuboidRenderer;
using Sx::Simulation::Simulations::MassSpringSimulation;
using Sx::Simulation::Collision::Models::MSM_TS_CollisionModel;
using Sx::Simulation::Objects::MassSpringMesh;
using Sx::Physics::Collision::Event::EulerCollisionEventPoolAllocator;
using Sx::SelfCCD::Handlers::Detection::SelfCCD_MSM_CollisionDetectionHandler;
using Sx::Simulation::Collision::Handlers::Response::MSM_TS_InverseVelocityResponseHandler;
using Sx::Simulation::Interface::MassSpringSimulationController;
using Sx::Simulation::Recording::MassSpringSimulationRecorder;
using Sx::Simulation::Recording::MassSpringSimulationRecording;
using Sx::Simulation::Interface::MassSpringSimulationReplayController;
using Sx::Vega::Storage::OBJ_VegaMassSpringMeshStorage;
using Sx::Simulation::Objects::Rendering::OpenGL_DefaultMassSpringMeshRenderer;

Example_Mass_Spring_Simulation_Timeline::Example_Mass_Spring_Simulation_Timeline(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) {
	ui.setupUi(this);

	//--------------------------------------------------------------------------
	// Setup Layout
	//--------------------------------------------------------------------------
	QGridLayout* gridLayout = new QGridLayout();
	gridLayout->setContentsMargins(2, 2, 2, 2);
	this->ui.viewportFrame->setLayout(gridLayout);

	this->openglContext = std::make_shared<OpenGL_Context>();

	this->openGL_Viewport0 = new QOpenGL_Viewport(this, this->openglContext);
	this->openGL_Viewport0->setRealtime(true);
	gridLayout->addWidget(this->openGL_Viewport0);

	this->openGL_Viewport1 = new QOpenGL_Viewport(this, this->openGL_Viewport0);
	this->openGL_Viewport1->setRealtime(true);
	gridLayout->addWidget(this->openGL_Viewport1);

	//--------------------------------------------------------------------------
	// Setup Collision.
	//--------------------------------------------------------------------------
	MSM_TS_CollisionModel* tscm = new MSM_TS_CollisionModel();
	EulerCollisionEventPoolAllocator<MassSpringMesh>* eulerAllocator = new EulerCollisionEventPoolAllocator<MassSpringMesh>();

	SelfCCD_MSM_CollisionDetectionHandler* ccd_msm_cdh = new SelfCCD_MSM_CollisionDetectionHandler();
	MSM_TS_InverseVelocityResponseHandler* msm_ts_ivrh = new MSM_TS_InverseVelocityResponseHandler();

	tscm->setCollisionDetectionHanlder(ccd_msm_cdh);
	tscm->setCollisionResponseHandler(msm_ts_ivrh);
	tscm->setAllocator(eulerAllocator);

	//--------------------------------------------------------------------------
	// Create a new mass-spring simulation.
	//--------------------------------------------------------------------------
	this->massSpringSimulation = std::make_shared<MassSpringSimulation>(tscm);
	this->massSpringSimulation->setTimeStepType(Sx::Simulation::FIXED);
	this->massSpringSimulation->setTimeStep(1.0 / 1000.0f);
	this->massSpringSimulation->pause();

	//--------------------------------------------------------------------------
	// Setup a new mass-spring controller.
	// Controller ownership is transfered to the OpenGL Viewport.
	//--------------------------------------------------------------------------
	this->mssController = std::make_shared<MassSpringSimulationController>(
		this->openGL_Viewport0, 
		std::make_shared<OpenGL_Canvas>(this->openglContext), 
		std::make_shared<OpenGL_PickingController>(), 
		std::make_shared<OpenGL_DefaultCameraRenderer>(this->openglContext), 
		this->massSpringSimulation
	);

	this->mssController->initialize();

	//--------------------------------------------------------------------------
	// Create the demo objects based on the provided object files.
	//--------------------------------------------------------------------------
	this->object1 = MassSpringMesh::Load(std::make_shared<OBJ_VegaMassSpringMeshStorage>().get(), std::make_shared<OpenGL_DefaultMassSpringMeshRenderer>(openglContext, 1.0f, 0.0f, 0.5f), "t1.obj");
	this->object2 = MassSpringMesh::Load(std::make_shared<OBJ_VegaMassSpringMeshStorage>().get(), std::make_shared<OpenGL_DefaultMassSpringMeshRenderer>(openglContext, 0.5f, 1.0f, 0.0f), "t2.obj");
	this->object3 = MassSpringMesh::Load(std::make_shared<OBJ_VegaMassSpringMeshStorage>().get(), std::make_shared<OpenGL_DefaultMassSpringMeshRenderer>(openglContext, 0.0f, 0.5f, 1.0f), "t3.obj");
	this->ground = MassSpringMesh::Load(std::make_shared<OBJ_VegaMassSpringMeshStorage>().get(), std::make_shared<OpenGL_DefaultMassSpringMeshRenderer>(openglContext, 0.2f, 0.2f, 0.4f), "ground.obj");

	this->object1->setSubsteps(5);
	this->object2->setSubsteps(5);
	this->object3->setSubsteps(5);
	this->ground->setStatic(true);

	this->massSpringSimulation->add(this->ground);
	this->massSpringSimulation->add(this->object1);
	this->massSpringSimulation->add(this->object2);
	this->massSpringSimulation->add(this->object3);

	//--------------------------------------------------------------------------
	// Timeline Controller
	//--------------------------------------------------------------------------
	this->timelineController = std::make_shared<FixedTimelineController>(
		this->openGL_Viewport1, 
		std::make_shared<OpenGL_Canvas>(this->openglContext), 
		std::make_shared<OpenGL_PickingController>(), 
		std::make_shared<OpenGL_DefaultCameraRenderer>(this->openglContext), 
		std::make_shared<OpenGL_DefaultPlotAxesRenderer>(this->openglContext), 
		std::make_shared<OpenGL_DefaultCuboidRenderer>(this->openglContext)
	);

	this->timelineController->initialize();
	this->timelineController->setDivisions(60);
	this->timelineController->setFrameCount(600);
	this->timelineController->setCurrentFrame(0);
	this->timelineController->setLabelInterval(1);

	//--------------------------------------------------------------------------
	// Recording
	//--------------------------------------------------------------------------
	this->testRecording = std::make_shared<MassSpringSimulationRecording>();
	this->mssRecorder = std::make_shared<MassSpringSimulationRecorder>(this->massSpringSimulation, this->testRecording);
	this->mssRecorder->setRecording(false);
	this->mssRecorder->addTimeline(this->timelineController);

	// Um if you dont do this it will crash..
	this->replayController = std::make_shared<MassSpringSimulationReplayController>(
		this->openGL_Viewport0, 
		std::make_shared<OpenGL_Canvas>(this->openglContext), 
		std::make_shared<OpenGL_PickingController>(), 
		std::make_shared<OpenGL_DefaultCameraRenderer>(this->openglContext), 
		this->massSpringSimulation, 
		this->testRecording
	);
	
	this->replayController->addTimeline(this->timelineController);

	// Reassign the mass spring simulation controller to viewport 0
	this->timelineController->setReplayable(this->replayController);

	this->openGL_Viewport0->setController(this->mssController);
	this->openGL_Viewport1->setController(this->timelineController);

	this->openGL_Viewport0->setClearColor(0.2f, 0.2f, 0.2f);
	this->openGL_Viewport1->setClearColor(0.2f, 0.2f, 0.2f);
}

Example_Mass_Spring_Simulation_Timeline::~Example_Mass_Spring_Simulation_Timeline() {}

void Example_Mass_Spring_Simulation_Timeline::onStartRecording() {
	this->massSpringSimulation->resume();
	this->mssRecorder->setRecording(true);
	this->timelineController->setInputEnabled(false);

	// ui
	this->ui.startRecordingButton->setEnabled(false);
	this->ui.stopRecordingButton->setEnabled(true);
}

void Example_Mass_Spring_Simulation_Timeline::onStopRecording() {
	// Stop recording and set the viewports controller to be the replay controller. Then start the animation from frame 0
	this->mssRecorder->setRecording(false);
	this->openGL_Viewport0->setController(this->replayController);
	this->replayController->resize(this->openGL_Viewport0->width(), this->openGL_Viewport0->height());
	this->replayController->pause();
	this->timelineController->setInputEnabled(true);

	this->ui.stopRecordingButton->setEnabled(false);
	this->ui.playButton->setEnabled(true);
	this->ui.pauseButton->setEnabled(true);
	this->ui.resetButton->setEnabled(true);
	this->ui.incrementButton->setEnabled(true);
	this->ui.decrementButton->setEnabled(true);

	// timeline??
	if ( this->testRecording.use_count() > 0 ) {
		unsigned int totalFrames = this->testRecording->getFrameCount();
		std::cout << "recorded: " << totalFrames << " frames" << std::endl;
		this->timelineController->setDivisions(60); // must! match fps
		this->timelineController->setFrameCount(totalFrames);
	}
}

void Example_Mass_Spring_Simulation_Timeline::onPlay() {
	this->replayController->setFrameIndex(this->timelineController->getCurrentTime());
	this->replayController->resume();
}

void Example_Mass_Spring_Simulation_Timeline::onPause() {
	this->replayController->pause();
}

void Example_Mass_Spring_Simulation_Timeline::onReset() {
	this->replayController->setFrameIndex(0);
	this->replayController->pause();
}

void Example_Mass_Spring_Simulation_Timeline::onIncrementFrame() {
	this->replayController->pause();
	this->replayController->incrementFrameIndex();
}

void Example_Mass_Spring_Simulation_Timeline::onDecrementFrame() {
	this->replayController->pause();
	this->replayController->decrementFrameIndex();
}
